const fs = require('fs')
const path = require('path')
const { parse } = require('node-html-parser')
const { glob } = require('glob')
const urlRegex = require('url-regex')

// 获取外连接的正则表达式
const regex = /https?:\/\/[^/]*/i
const urls = new Set()

// 遍历dist目录下所有的文件  查找匹配域名
async function serachDomain() {
  const files = await glob('dist/**/*.{js,css,html}')
  files.forEach(path => {
    const source = fs.readFileSync(path, { encoding: 'utf-8' })
    const matches = source.match(urlRegex({ strict: true }))
    if (matches) {
      matches.forEach(str => {
        const match = str.match(regex)
        if (match && match[0]) {
          urls.add(match[0])
        }
      })
    }
  })
}

// 把所有的域名插入到html头部，进行dns预解析
async function insertLinks() {
  const files = await glob('dist/**/*.html')
  const links = [...urls].map(url => `<link rel="dns-prefetch" href=${url} />`).join('\n')
  for (const file of files) {
    const htmlStr = fs.readFileSync(file, { encoding: 'utf-8' })
    const html = parse(htmlStr)
    const head = html.querySelector('head')
    head.insertAdjacentHTML('afterbegin', links)
    fs.writeFileSync(file, html.toString())
  }
}

async function main() {
  await serachDomain()
  await insertLinks()
}

main()
